package weaver.interfaces.jinzhou.cronjob;


import com.weaver.general.TimeUtil;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.schedule.BaseCronJob;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Stream;

/**
 * @version 1.0
 * @Title ecology-9
 * @Company 泛微软件
 * @CreateDate 2025/06/11
 * @Description 宿舍记录
 * @Author Lee
 */
public class DormitoryRecordJob extends BaseCronJob {
    private BaseBean bb = new BaseBean();
    private String currentDay;
    private String formmodeId;

    @Override
    public void execute() {
        String currentDateString = TimeUtil.getCurrentDateString();
        String month = currentDateString.substring(0, 7);
        if (StringUtils.isNotEmpty(currentDay) && currentDateString.compareTo(currentDay) >= 0) {
            month = currentDay.substring(0, 7);
        } else {
            currentDay = currentDateString;
        }

        try {
            RecordSet rs = new RecordSet();
            //查询月度汇总记录表，当月数据，决定更新还是插入
            String sql = "select concat(ryxm,ssxx) as flag " +
                    "from uf_zsjljmglbb " +
                    "where yf=?";
            rs.executeQuery(sql, month);
            HashSet<String> existSet = new HashSet<>();
            while (rs.next()) {
                existSet.add(rs.getString("flag"));
            }

            List<List> updateList = new ArrayList<>();
            List<List> insertList = new ArrayList<>();

            //查询离宿日期小于本月末的数据，计算入住时长,最后更新或者新增
            getUpdateOrInsert(month, rs, existSet, updateList, insertList);

            String insertSql = "insert into uf_zsjljmglbb (ts,FORMMODEID,ryxm,ssxx,yf) values (?,?,?,?,?)";
            String updateSql = "update uf_zsjljmglbb set ts=? where FORMMODEID=? and ryxm=? and ssxx=? and yf=?";
            rs.executeBatchSql(insertSql, insertList);
            rs.executeBatchSql(updateSql, updateList);
        } catch (Exception e) {
            bb.writeLog("DormitoryRecordJob-e-" + e.getMessage());
        }
    }

    private void getUpdateOrInsert(String month, RecordSet rs, HashSet<String> existSet, List<List> updateList, List<List> insertList) {
        String sql;
        String beginDay = month + "-01";
        String lastDay = getLastDayOfMonth(month);
        sql = "select zsry,szss,rzrq,lsrq " +
                "from uf_zsxxgljmb " +
                "where lsrq is null or (lsrq>=? and lsrq<=?)";
        rs.executeQuery(sql, beginDay, lastDay);

        while (rs.next()) {
            String userId = rs.getString("zsry");
            String szss = rs.getString("szss");
            String flag = userId + szss;
            String rzrq = rs.getString("rzrq");
            String lsrq = rs.getString("lsrq");
            //住的天数
            int days = 0;
            //入住日期在本月
            if (rzrq.compareTo(beginDay) >= 0) {
                days = calculateDiff(rzrq, lsrq);
            } else {
                //入住日期在本月之前
                days = calculateDiff(beginDay, lsrq);
            }
            ArrayList<Object> list = new ArrayList<>();
            list.add(days);
            list.add(formmodeId);
            list.add(userId);
            list.add(szss);
            list.add(month);
            if (existSet.contains(flag)) {
                //更新
                updateList.add(list);
            } else {
                //新增
                insertList.add(list);
            }
        }
    }

    private int calculateDiff(String rzrq, String lsrq) {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 解析日期字符串
        LocalDate date1 = LocalDate.parse(rzrq, formatter);
        LocalDate date3 = LocalDate.parse(currentDay, formatter);

        int days = 0;
        if (StringUtils.isNotEmpty(lsrq)) {
            LocalDate date2 = LocalDate.parse(lsrq, formatter);
            //离宿日期小于等于当前时间
            if (lsrq.compareTo(currentDay) <= 0) {
                days = (int) Math.abs(ChronoUnit.DAYS.between(date1, date2));
            } else {
                //离宿日期大于当前时间
                days = (int) Math.abs(ChronoUnit.DAYS.between(date1, date3));
            }
        } else {
            days = (int) Math.abs(ChronoUnit.DAYS.between(date1, date3));
        }
        // 计算天数差（绝对值）
        return days;
    }

    private String getLastDayOfMonth(String month) {
        // 解析年月字符串
        YearMonth yearMonth = YearMonth.parse(month, DateTimeFormatter.ofPattern("yyyy-MM"));
        // 获取该月的最后一天
        LocalDate endDate = yearMonth.atEndOfMonth();
        return endDate.toString();
    }
}
